package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.to.SkusHasStockTo;
import com.atguigu.common.utils.DataUtil;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.entity.WareInfoEntity;
import com.atguigu.gulimall.ware.feign.ProductFeignService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.WareSkuDao;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.service.WareSkuService;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    WareSkuDao wareSkuDao;

    @Autowired
    ProductFeignService productFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String skuId = (String) params.get("skuId");
        String wareId = (String) params.get("wareId");
        Wrapper<WareSkuEntity> wrapper = new LambdaQueryWrapper<WareSkuEntity>()
                .eq(DataUtil.isNotEmpty(skuId), WareSkuEntity::getSkuId, skuId)
                .eq(DataUtil.isNotEmpty(wareId), WareSkuEntity::getWareId, wareId);
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        return pageUtils;
    }


    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //1、判断如果还没有这个库存记录新增
        List<WareSkuEntity> entities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if (entities == null || entities.size() == 0) {
            WareSkuEntity skuEntity = new WareSkuEntity();
            skuEntity.setSkuId(skuId);
            skuEntity.setStock(skuNum);
            skuEntity.setWareId(wareId);
            skuEntity.setStockLocked(0);
            //TODO 远程查询sku的名字，如果失败，整个事务无需回滚
            //1、自己catch异常
            //TODO 还可以用什么办法让异常出现以后不回滚？高级
            try {
                R info = productFeignService.info(skuId);
                Map<String, Object> data = (Map<String, Object>) info.get("skuInfo");

                if (info.getCode() == 0) {
                    skuEntity.setSkuName((String) data.get("skuName"));
                }
            } catch (Exception e) {

            }
            wareSkuDao.insert(skuEntity);
        } else {
            wareSkuDao.addStock(skuId, wareId, skuNum);
        }
    }

    @Override
    public List<SkusHasStockTo> getSkusHasStock(List<Long> skuIds) {
        LambdaQueryWrapper<WareSkuEntity> query = new LambdaQueryWrapper<WareSkuEntity>().in(WareSkuEntity::getSkuId, skuIds);
        List<WareSkuEntity> list = this.list(query);
        TreeMap<Long, List<WareSkuEntity>> collect = new TreeMap<>();
        if (DataUtil.isNotEmpty(list)) {
            collect = list.stream()
                    .collect(Collectors.groupingBy(WareSkuEntity::getSkuId, TreeMap::new, Collectors.toList()));
        }
        TreeMap<Long, List<WareSkuEntity>> finalCollect = collect;
        List<SkusHasStockTo> tos = skuIds.stream().map(item -> {
            SkusHasStockTo to = new SkusHasStockTo();
            to.setSkuId(item);
            to.setHasStock(false);
            if (finalCollect.containsKey(item)) {
                List<WareSkuEntity> skuEntities = finalCollect.get(item);
                for (WareSkuEntity entity : skuEntities) {
                    if (entity.getStock() - entity.getStockLocked() > 0) {
                        to.setHasStock(true);
                        break;
                    }
                }
            }
            return to;
        }).collect(Collectors.toList());
        return tos;
    }
}
